package com.tspark.tspark1.service.impl;

import com.tspark.tspark1.mapper.UserMapper;
import com.tspark.tspark1.service.UserService;
import com.tspark.tspark1.zoo.constant.MessageConstant;
import com.tspark.tspark1.zoo.exception.LoginFailedException;
import com.tspark.tspark1.zoo.exception.RegisterFailedException;
import com.tspark.tspark1.zoo.pojo.dto.LoginDTO;
import com.tspark.tspark1.zoo.pojo.entity.User;
import com.tspark.tspark1.zoo.pojo.vo.LoginVO;
import com.tspark.tspark1.zoo.util.CryptoUtil;
import com.tspark.tspark1.zoo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private CryptoUtil cryptoUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public LoginVO register(LoginDTO loginDTO) {
        //将密码加密
        loginDTO.setPassword(cryptoUtil.sha256(loginDTO.getPassword()));
        //检查有没有重复数据
        User userByUsername = userMapper.getUserByUsername(loginDTO.getUsername());
        if (userByUsername != null) {
            throw new RegisterFailedException(MessageConstant.USERNAME_DUPLICATE);
        }
        userMapper.register(loginDTO);
        int id = loginDTO.getId();
        //注册成功后返回LoginVO
        return new LoginVO(id, loginDTO.getUsername(), jwtUtil.genAccessToken(id,0));
    }

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        //将密码加密
        loginDTO.setPassword(cryptoUtil.sha256(loginDTO.getPassword()));
        //比对密码
        User userByUsername = userMapper.getUserByUsername(loginDTO.getUsername());
        if (userByUsername == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        if (!userByUsername.getPassword().equals(loginDTO.getPassword())) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        int id = userByUsername.getId();
        int isAdmin = userByUsername.getAdmin();
        return new LoginVO(id, userByUsername.getUsername(), jwtUtil.genAccessToken(id, isAdmin));
    }
}
